'use strict';
import Base from './base.js';

export default class extends Base {
  // 充值单列表
  async rechargelistAction() {
    const page = JSON.parse(this.post('page'));
    /* let zt = page.zt*1?[0]:[1,2]; */
    const shopid = this.shop_userinfo.departmentid;
    const where = {
      's.departmentid': shopid,
      's.ordertype': 3,
      'g.name|g.vipcard|a.name|z.name|g.phone|s.remarks': ['like', '%' + page.search + '%']
    };
    if (page.zt != 3) {
      where['s.status'] = page.zt;
    }

    // 设置时间
    if (page.times && (page.times[0] != null && page.times[1] != null)) {
      const begintime = Math.floor(new Date(page.times[0]).setHours(0, 0, 0, 0) / 1000);
      const endtime = Math.floor(new Date(page.times[1]).setHours(0, 0, 0, 0) / 1000) + 86400;
      where['s.addtime'] = {'>=': begintime, '<': endtime};
    }

    const list = await this.model('or_shop_order')
      .alias('s')
      .join('think_or_guest g on s.guestid = g.id')
      .join('`think_or_department` d on g.departmentid = d.id')
      .join('think_or_admin a on s.operatorid = a.id')
      .join('think_or_admin z on s.auditorid = z.id')
      .join('think_or_shop_orderinfo oi on oi.orderid = s.id and oi.type=5')
      .field('s.*,g.name as gname,g.phone as gphone,g.vipcard,a.name as aname,z.name as zname,oi.price,d.name as shopname')
      .where(where)
      .page(page.pages, page.limits)
      .order('s.addtime desc')
      .countSelect();

    return this.json(list);
  }

  // 删除充值单
  async deleterechargeorderAction() {
    const id = this.post('id');
    /*
    * 1、第一步先判断当前订单是否已删除
    * 2、判断当前订单是否已经结账或者审核
    */
    const isdel = await this.model('or_shop_order').where({id: id, status: 0}).find();
    if (think.isEmpty(isdel)) {
      return this.fail('该订单已结账或已删除');
    }
    // 删除订单表和订单附属表
    const model = this.model('or_shop_order');
    await model.transaction(async() => {
      try {
        const resorder = await model.where({id: id}).delete();
        const resorderinfo = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: id}).delete();
        if (!resorder && !resorderinfo) {
          await model.rollback();
          return this.fail('删除失败');
        }
        await model.commit();
        return this.success('删除成功');
      } catch (e) {
        await model.rollback();
        return this.fail('删除失败');
      }
    });
  }

  // 充值反结账
  async fanpayAction() {
    const id = this.post('id');

    // 判断状态是否满足
    const oinfo = await this.model('or_shop_order').where({id: id}).find();

    const isCanEditOrder = await this.isCanEditOrder(id, 'CZD');
    if (!isCanEditOrder) {
      return this.fail('暂不允许操作其他店单据！');
    }
    // 判断订单状态
    if (oinfo.status != 1) {
      return this.fail('该单据未结账或已经分配业绩');
    }

    const shopid = this.shop_userinfo.departmentid;

    const model = this.model('or_shop_order');
    await model.transaction(async() => {
      try {
        /*
        * 收款账户循环返还金额，删除日志
        * 减去客户的账户金额和产生的积分，删除个人账户日志记录和积分产生记录
        * 减去现金业绩日志
        * 有赠送产品增加库存，删除库存日志
        * 有暂存的删除暂存信息
        */

        // 收款账户日志查找
        const accountlog = await this.model('or_shop_accountlog').db(model.db()).where({ordertype: 'CZD', orderid: id}).select();

        let resaccount = 1;
        let resaccountlog = 1;

        if (accountlog.length > 0) {
          const accountlist = [];
          for (var i = accountlog.length - 1; i >= 0; i--) {
            const account = await this.model('or_shop_account').db(model.db()).where({id: accountlog[i].accountid}).find();

            account.balance -= Number(accountlog[i].money);

            accountlist.push(account);
          }
          resaccount = await this.model('or_shop_account').db(model.db()).updateMany(accountlist);

          resaccountlog = await this.model('or_shop_accountlog').db(model.db()).where({ordertype: 'CZD', orderid: id}).delete();
        }

        // 找出客户账户日志
        // 判断是否有积分赠送，如果有则返还积分并删除积分日志
        const guestaccountlog = await this.model('or_shop_guest_accountlog').db(model.db()).where({ordertype: 'CZD', orderid: id}).find();

        let resguestaccount = 1;
        let resguestaccountlog = 1;

        if (guestaccountlog.balance != 0 || guestaccountlog.giftbalance != 0) {
          const guest = await this.model('or_guest').db(model.db()).where({id: guestaccountlog.guestid}).find();

          const integralLog = await this.model('or_shop_jifenlog').db(model.db()).where({shopid: shopid, type: 3, orderid: id}).find();

          const gengxinGuestYuE = {
            balance: guest.balance - Number(guestaccountlog.balance),
            giftbalance: guest.giftbalance - Number(guestaccountlog.giftbalance)
          };

          if (!think.isEmpty(integralLog)) {
            gengxinGuestYuE.score = guest.score - Number(integralLog.jifen);
            const delJifenLog = await this.model('or_shop_jifenlog').db(model.db()).where({shopid: shopid, type: 3, orderid: id}).delete();
            if (!delJifenLog) {
              await model.rollback();
              return this.fail('返还积分失败');
            }
          }

          resguestaccount = await this.model('or_guest').db(model.db()).where({id: guestaccountlog.guestid}).update(gengxinGuestYuE);

          resguestaccountlog = await this.model('or_shop_guest_accountlog').db(model.db()).where({ordertype: 'CZD', orderid: id}).delete();
        }

        // 查看商品日志
        const goodslog = await this.model('or_shop_goodslog').db(model.db()).where({orderid: id, ordertype: 'CZD'}).select();

        let resgoods = 1;
        let resgoodslog = 1;
        if (goodslog.length > 0) {
          const goodsdata = [];
          for (var i = goodslog.length - 1; i >= 0; i--) {
            const goods = await this.model('or_shop_goods').db(model.db()).where({goodsid: goodslog[i].goodsid, shopid: shopid}).find();
            goods.nums -= Number(goodslog[i].nums);
            goodsdata.push(goods);
          }
          resgoods = await this.model('or_shop_goods').db(model.db()).updateMany(goodsdata);
          resgoodslog = await this.model('or_shop_goodslog').db(model.db()).where({orderid: id, ordertype: 'CZD'}).delete();
        }

        // 删除暂存的信息
        const reszancun = await this.model('or_shop_guest_temp_reserve').db(model.db()).where({orderid: id}).delete();

        // 删除客户卡项表赠送的项目
        const reskxsub = await this.model('or_shop_guestcardsubject').db(model.db()).where({shopid: shopid, orderid: id}).delete();

        // 除去现金业绩
        const resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).where({feattype: 'CZD', orderid: id}).select();

        const resticheng = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, ordertype: 'CZD', orderid: id}).select();

        if (resxianjin.length && resticheng.length) {
          const delYejis = await this.model('or_shop_yejixianjin').db(model.db()).where({orderid: id}).delete();

          const delTichengs = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, ordertype: 'CZD', orderid: id}).delete();

          if (!delYejis && !delTichengs) {
            await model.rollback();
            return this.fail('清除现金业绩失败');
          }
        }

        // 更改单据信息
        const resorder = await model.where({id: id}).update({status: 0, auditorid: 0});

        if (resaccount && resaccountlog && resguestaccount && resguestaccountlog && resgoods && resgoodslog && reszancun !== false && reskxsub !== false && resorder) {
          await model.commit();
          return this.success({code: 200, info: '反结账成功', status: 0});
        } else {
          await model.rollback();
          return this.fail('反结账失败');
        }
      } catch (e) {
        // console.log(e);
        await model.rollback();
        return this.fail('反结账失败');
      }
    });
  }

  // 获取机构会员等级
  async getvipgradeAction() {
    const shopid = this.shop_userinfo.departmentid;
    const viplist = await this.model('or_department')
      .alias('d')
      .field('v.*')
      .join('`think_or_guest_vipgrade` v on v.departmentid=d.pid or v.departmentid=0')
      .where({'d.id': shopid})
      .select();
    return this.json(viplist);
  }

  // query shop guest of remote
  async queryguestlistAction() {
    const query = this.get('query');
    const shopid = this.shop_userinfo.departmentid;

    const orid = await this.model('or_department').where({id: shopid}).getField('pid', true);

    const shoplist = await this.model('or_department')
      .alias('s')
      .join('`think_or_department` d on d.id=s.pid')
      .where({'s.pid': orid})
      .getField('s.id');

    const list = await this.model('or_guest')
      .alias('g')
      .field('g.*,v.vipname')
      .join('`think_or_guest_vipgrade` v on v.id=g.level')
      .where('g.departmentid IN (' + shoplist + ') AND g.initial_info = 1 AND (g.vipcard LIKE "' + query + '" OR g.phone LIKE "' + query + '")')
      .select();

    return this.json(list);
  }

  // 客户欠款列表
  async debtlistAction() {
    /* let pages = this.post('pages');
    let limits = this.post('limits');
    let search = this.post('search'); */
    const page = JSON.parse(this.post('page'));
    const where = {
      departmentid: this.shop_userinfo.departmentid,
      balance: ['<', 0],
      'name|phone|vipcard': ['like', '%' + page.search + '%']
    };
    const list = await this.model('or_guest')
      .where(where)
      .page(page.currentSize, page.pageSize)
      .countSelect();
    return this.json(list);
  }

  async getguestAction() {
    const gid = this.get('gid');
    const ginfo = await this.model('or_guest').where({id: gid}).find();
    return this.json(ginfo);
  }

  // 根据tp判断当前get的是产品还是项目
  async getalllistAction() {
    const shopid = this.shop_userinfo.departmentid;

    const goods = await this.model('or_shop_goods')
      .alias('s')
      .field('s.*,g.id as pxid,g.name,g.number,IFNULL(null, 1) as type,g.brandid')
      .join('`think_or_goods` g on g.id=s.goodsid')
      .where({'s.shopid': shopid, 's.isdisable': 0})
      .select();

    const subject = await this.model('or_shop_subject')
      .alias('s')
      .field('s.*,g.id as pxid, g.name,g.number,IFNULL(null, 2) as type,g.brandid')
      .join('`think_or_subject` g on g.id=s.subjectid')
      .where({'s.shopid': shopid, 's.isdisable': 0})
      .select();

    const alist = await this.model('or_shop_account').where({departmentid: shopid, isdisable: 0}).select();

    const ulist = await this.model('or_app_user').where({shopid: shopid, isdisable: 0}).select();

    const basis = await this.model('or_shop_basis').where({shopid: shopid}).find();

    const data = {
      goods: goods,
      subject: subject,
      alist: alist,
      ulist: ulist,
      basis: basis
    };

    return this.json(data);
  }

  // 获取充值单信息
  async getoinfoAction() {
    const oid = this.get('oid');

    const shopid = this.shop_userinfo.departmentid;

    const oInfo = await this.model('or_shop_order')
      .alias('o')
      .field('o.*,u.name')
      .join('`think_or_app_user` u on o.gendanid=u.id')
      .where({'o.id': oid})
      .find();

    const gInfo = await this.model('or_guest')
      .alias('g')
      .field('g.*,v.vipname')
      .join('`think_or_guest_vipgrade` v on v.id=g.level')
      .where({'g.id': oInfo.guestid})
      .find();

    const oList = await this.model('or_shop_orderinfo').where({departmentid: shopid, orderid: oid}).select();

    const data = {
      oInfo: oInfo,
      gInfo: gInfo,
      oList: oList
    };

    let aList = [];
    let uList = [];
    let tList = [];
    if (oInfo.status > -1) {
      aList = await this.model('or_shop_accountlog')
        .alias('l')
        .field('l.money, a.id, a.name')
        .join('`think_or_shop_account` a on a.id=l.accountid')
        .where({'l.departmentid': shopid, 'l.ordertype': 'CZD', 'l.orderid': oid})
        .select();

      uList = await this.model('or_shop_yejiticheng')
        .alias('t')
        .field('t.id,t.addtype,t.xianjinyeji,t.userid,u.name,u.bumenid,u.xiaozuid')
        .join('`think_or_app_user` u on u.id=t.userid')
        .where({'t.shopid': shopid, 't.orderid': oid, 't.ordertype': 'CZD'})
        .select();

      data.aList = aList || [];
      data.uList = uList || [];
      if (oInfo.status > 0) {
        // 查询是否开通了阶梯提成
        // const baseConfig = await this.model('or_shop_basis').where({shopid: this.shop_userinfo.departmentid}).find();

        tList = await this.model('or_shop_yejiticheng')
          .alias('t')
          .field('t.id,t.addtype,t.xianjinyeji,IF(t.addtype>0,t.qitaticheng,t.xianjinticheng) as xianjinticheng, t.xianjinjieti, t.userid,u.name, t.addtime')
          .join('`think_or_app_user` u on u.id=t.userid')
          .where({'t.shopid': shopid, 't.orderid': oid, 't.ordertype': 'CZD'})
          .select();

        data.tList = tList || [];
      }
    }

    return this.json(data);
  }

  async getFeatInfoAction() {
    const ulist = JSON.parse(this.get('ulist'));
    // 查询是否开通了阶梯提成
    const baseConfig = await this.model('or_shop_basis').where({shopid: this.shop_userinfo.departmentid}).find();
    const orderaddtime = await this.model('or_shop_order').where({id: this.get('id')}).getField('addtime', true);

    const dates = new Date(orderaddtime * 1000);
    const beginToday = dates.setHours(0, 0, 0, 0) / 1000;
    const beginMonth = new Date(dates.getFullYear(), dates.getMonth()).getTime() / 1000;
    const beginYear = new Date(dates.getFullYear(), 0).getTime() / 1000;

    if (ulist.length > 0) {
      for (let i = 0; i < ulist.length; i++) {
        if (ulist[i].id > 0) {
          ulist[i].xianjinxinxi = [];
          ulist[i].xianjinjieti = 0;
          if (baseConfig && baseConfig.isticheng) {
            // 取本月开始时间戳
            ulist[i].userfeat = await this.model('or_shop_yejiticheng')
              .field('sum(if(addtime > ' + beginToday + ', xianjinyeji, 0)) as todayxj, sum(if(addtime > ' + beginMonth + ', xianjinyeji, 0)) as monthxj, sum(if(addtime > ' + beginYear + ', xianjinyeji, 0)) as yearxj')
              .where({userid: ulist[i].id, addtime: {'>=': beginYear, '<=': orderaddtime}}).find();
            // 取出配置
            const cf = JSON.parse(baseConfig.tichengarr || '[]');
            if (cf.length) {
              for (let m = 0; m < cf.length; m++) {
                switch (cf[m].timetype) {
                  case 1:
                    if (cf[m].feattype == 1) {
                      if (cf[m].feet <= ulist[i].userfeat.yearxj) {
                        // console.log(1)
                        ulist[i].xianjinjieti += ulist[i].money * cf[m].percent / 100;
                        ulist[i].xianjinxinxi.push(ulist[i].name + '年度现金业绩为' + ulist[i].userfeat.yearxj + '元，获得年度现金业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + ulist[i].money * cf[m].percent / 100 + '元');
                      }
                    }
                    break;
                  case 2:
                    if (cf[m].feattype == 1) {
                      if (cf[m].feet <= ulist[i].userfeat.monthxj) {
                        // console.log(2)
                        ulist[i].xianjinjieti += ulist[i].money * cf[m].percent / 100;
                        ulist[i].xianjinxinxi.push(ulist[i].name + '月度现金业绩为' + ulist[i].userfeat.monthxj + '元，获得月度现金业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + ulist[i].money * cf[m].percent / 100 + '元');
                      }
                    }
                    break;
                  case 3:
                    if (cf[m].feattype == 1) {
                      if (cf[m].feet <= ulist[i].userfeat.todayxj) {
                        // console.log(3);
                        ulist[i].xianjinjieti += ulist[i].money * cf[m].percent / 100;
                        ulist[i].xianjinxinxi.push(ulist[i].name + '当日现金业绩为' + ulist[i].userfeat.todayxj + '元，获得当日现金业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + ulist[i].money * cf[m].percent / 100 + '元');
                      }
                    }
                    break;
                }
              }
            }
          }
          ulist[i].xianjinjieti = ulist[i].xianjinjieti.toFixed(2);
        }
      }
    }

    return this.json(ulist);
  }

  /** ************************ 充值流程 ************************/
  // 保存并编辑订单
  async gooneAction() {
    const data = JSON.parse(this.post('data'));

    const shopid = this.shop_userinfo.departmentid;

    const aid = this.shop_userinfo.id;

    if (data.oid) {
      const zt = await this.model('or_shop_order').where({id: data.oid}).find();
      if (zt.status > 0) {
        return this.fail('当前订单已经结账');
      }
    }

    const time = Math.round(Date.now() / 1000);
    let ordersn;
    if (!data.oid) {
      ordersn = await this.getordersn('CZD', 1);
    }

    const model = this.model('or_shop_order');

    await model.transaction(async() => {
      try {
        let orderid = 0;
        if (data.oid) {
          const gxOinfoOne = await model.where({id: data.oid}).update({
            recemoney: data.bala * 1,
            operatorid: aid,
            remarks: data.remarks,
            gendanid: data.gdid,
            iscross: data.crossShop
          });

          const delOinfoList = await this.model('or_shop_orderinfo').db(model.db()).where({departmentid: shopid, orderid: data.oid}).delete();

          const adOinfoOne = [];
          if (data.bala * 1) {
            adOinfoOne.push({
              orderid: data.oid,
              departmentid: shopid,
              type: 4,
              typeid: data.level,
              typename: '充值金额',
              num: 1,
              price: data.bala,
              totalprice: data.bala * 1,
              discount: 1,
              amount: data.bala * 1,
              yejitype: 2,
              istemp: 0,
              usemoney: data.bala * 1,
              isgift: 0,
              brandid: 0
            });
          }
          if (data.gift * 1) {
            adOinfoOne.push({
              orderid: data.oid,
              departmentid: shopid,
              type: 5,
              typeid: data.level,
              typename: '赠送金额',
              num: 1,
              price: data.gift,
              totalprice: data.gift * 1,
              discount: 1,
              amount: data.gift * 1,
              yejitype: 2,
              istemp: 0,
              usemoney: 0,
              isgift: 0,
              brandid: 0
            });
          }
          if (data.giftpx.length) {
            for (var j = 0, pxlen = data.giftpx.length; j < pxlen; j++) {
              if (data.giftpx[j].id) {
                adOinfoOne.push({
                  orderid: data.oid,
                  departmentid: shopid,
                  type: data.giftpx[j].type,
                  typeid: data.giftpx[j].id,
                  typename: data.giftpx[j].name,
                  num: data.giftpx[j].num,
                  price: data.giftpx[j].price,
                  totalprice: data.giftpx[j].price,
                  discount: 0,
                  amount: 0,
                  yejitype: 2,
                  istemp: 1,
                  usemoney: 0,
                  isgift: 1,
                  brandid: data.giftpx[j].brandid
                });
              }
            }
          }

          const adOinfoRes = await this.model('or_shop_orderinfo').db(model.db()).addMany(adOinfoOne);

          if (!gxOinfoOne && !delOinfoList && !adOinfoRes) {
            await model.rollback();
            return this.fail('保存失败');
          }
        } else {
          const addorder = {
            'order_sn': ordersn,
            'guestid': data.gid,
            'departmentid': shopid,
            'recemoney': data.bala * 1,
            'ordertype': 3,
            'operatorid': aid,
            'addtime': time,
            'remarks': data.remarks,
            'gendanid': data.gdid,
            'iscross': data.crossShop
          };
          orderid = await model.add(addorder);

          const addorder_one = [];
          if (data.bala * 1) {
            addorder_one.push({
              orderid: orderid,
              departmentid: shopid,
              type: 4,
              typeid: data.level,
              typename: '充值金额',
              num: 1,
              price: data.bala,
              totalprice: data.bala * 1,
              discount: 1,
              amount: data.bala * 1,
              yejitype: 2,
              istemp: 0,
              usemoney: data.bala * 1,
              isgift: 0,
              brandid: 0
            });
          }
          if (data.gift * 1) {
            addorder_one.push({
              orderid: orderid,
              departmentid: shopid,
              type: 5,
              typeid: data.level,
              typename: '赠送金额',
              num: 1,
              price: data.gift,
              totalprice: data.gift * 1,
              discount: 1,
              amount: data.gift * 1,
              yejitype: 2,
              istemp: 0,
              usemoney: 0,
              isgift: 0,
              brandid: 0
            });
          }
          if (data.giftpx.length) {
            for (let j = 0, pxlen = data.giftpx.length; j < pxlen; j++) {
              if (data.giftpx[j].id) {
                addorder_one.push({
                  orderid: orderid,
                  departmentid: shopid,
                  type: data.giftpx[j].type,
                  typeid: data.giftpx[j].id,
                  typename: data.giftpx[j].name,
                  num: data.giftpx[j].num,
                  price: data.giftpx[j].price,
                  totalprice: data.giftpx[j].price,
                  discount: 0,
                  amount: 0,
                  yejitype: 2,
                  istemp: 1,
                  usemoney: 0,
                  isgift: 1,
                  brandid: data.giftpx[j].brandid
                });
              }
            }
          }

          const addorderRes = await this.model('or_shop_orderinfo').db(model.db()).addMany(addorder_one);

          if (!orderid && !addorderRes) {
            await model.rollback();
            return this.fail('保存失败');
          }
        }

        const saveRemarks = await this.model('or_guest').db(model.db()).where({id: data.gid}).update({remarks: data.gremarks});

        if (!saveRemarks) {
          await model.rollback();
          return this.fail('更新客户描述');
        }

        const oid = orderid || data.oid;

        await model.commit();
        return this.success({code: 200, info: '保存成功', orderid: oid, status: 0});
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('开单失败');
      }
    });
  }

  // 结账
  async gotwoAction() {
    const data = JSON.parse(this.post('data'));

    if (data.oid) {
      const zt = await this.model('or_shop_order').where({id: data.oid}).find();

      if (zt.status > 0) {
        return this.fail('当前订单已结账');
      }
    }

    const shopid = this.shop_userinfo.departmentid;

    const aid = this.shop_userinfo.departmentid;

    const basis = await this.model('or_shop_basis').where({shopid: shopid}).find();

    const time = Math.round(Date.now() / 1000);

    const model = this.model('or_shop_order');

    await model.transaction(async() => {
      try {
        const oinfo = await model.where({id: data.oid}).find();

        const olist = await this.model('or_shop_orderinfo').db(model.db()).where({departmentid: shopid, orderid: data.oid}).select();

        let bala = 0, gift = 0, pxs = [], level = 0;
        olist.forEach((v) => {
          if (v.type === 4) {
            bala = v.price;
            level = v.typeid;
          }
          if (v.type === 5) {
            gift = v.price;
            level = v.typeid;
          }
          if (v.type === 1 || v.type === 2) {
            pxs.push(v);
          }
        });

        // 记录客户账户充值记录
        const guestAccountLog = {
          guestid: oinfo.guestid,
          shopid: shopid,
          ordertype: 'CZD',
          orderid: data.oid,
          balance: bala,
          giftbalance: gift,
          addtime: oinfo.addtime,
          type: 1
        };

        const addGuestAccountLog = await this.model('or_shop_guest_accountlog').db(model.db()).add(guestAccountLog);

        // 如果有现金收益且当前分店有设置积分比则记录客户的积分日志
        if (bala && basis.jifenpercent && basis.jifenpercent > 0) {
          const guestScoreLog = {
            shopid: shopid,
            guestid: oinfo.guestid,
            type: 3,
            money: bala,
            jifen: Math.floor(bala * basis.jifenpercent),
            orderid: data.oid,
            addtime: oinfo.addtime
          };
          const addGuestScoreLog = await this.model('or_shop_jifenlog').db(model.db()).add(guestScoreLog);
          if (!addGuestScoreLog) {
            await model.rollback();
            return this.fail('记录积分失败');
          }
        }

        // 更新客户信息（balance,giftbalance,level,arrivetime,score）
        const ginfo = await this.model('or_guest').db(model.db()).where({id: oinfo.guestid}).find();

        const guestInfo = {
          balance: Number(ginfo.balance + bala).toFixed(2),
          giftbalance: Number(ginfo.giftbalance + gift).toFixed(2),
          level: level,
          arrivetime: oinfo.addtime,
          score: Number(ginfo.score + bala * basis.jifenpercent).toFixed(0)
        };

        const updateGuestInfo = await this.model('or_guest').db(model.db()).where({id: oinfo.guestid}).update(guestInfo);

        if (!updateGuestInfo && !addGuestAccountLog) {
          await model.rollback();
          return this.fail('更新客户余额和积分信息失败');
        }

        // 如果存在赠送的品项，则把赠送的品项分别存入or_shop_guestcardsubject和or_shop_guest_temp_reserve表
        // 并且根据赠送的产品减去相应的库存，并记录库存流动日志
        if (pxs.length) {
          let slist = [], glist = [];
          pxs.forEach((v) => {
            if (v.id && v.type === 1) {
              glist.push({
                guestid: oinfo.guestid,
                goodsid: v.typeid,
                price: v.price,
                num: v.num,
                nownum: v.num,
                orderid: data.oid,
                shopid: shopid,
                addtime: oinfo.addtime,
                isgift: 1,
                brandid: v.brandid
              });
            } else if (v.id && v.type === 2) {
              slist.push({
                guestid: oinfo.guestid,
                subjectid: v.typeid,
                num: v.num,
                nownum: v.num,
                price: v.price,
                cardtype: 2,
                orderid: data.oid,
                addtime: oinfo.addtime,
                shopid: shopid
              });
            }
          });

          let addGuestCardSubject = 1, addTempReserve = 1, addDecreGoodsLog = 1, updateDecreGoodsRes = 1;
          if (slist.length) {
            addGuestCardSubject = await this.model('or_shop_guestcardsubject').db(model.db()).addMany(slist);
          }

          // 如果有赠送的产品，则减去产品相应的库存，如果库存不足则不能充值

          if (glist.length) {
            addTempReserve = await this.model('or_shop_guest_temp_reserve').db(model.db()).addMany(glist);

            let decreGoods = [], decreGoodsLog = [];
            for (var i = glist.length - 1; i >= 0; i--) {
              const shopGoods = await this.model('or_shop_goods').db(model.db()).where({shopid: shopid, goodsid: glist[i].goodsid}).find();

              decreGoods.push({
                id: shopGoods.id,
                nums: shopGoods.nums - glist[i].num
              });

              if (shopGoods.nums - glist[i].num < 0) {
                await model.rollback();
                return this.fail('产品库存剩余数量不足');
              }

              decreGoodsLog.push({
                departmentid: shopid,
                goodsid: glist[i].goodsid,
                ordertype: 'CZD',
                orderid: data.oid,
                nums: -glist[i].num,
                addtime: oinfo.addtime,
                posttime: oinfo.addtime
              });
            }

            if (decreGoods.length) {
              updateDecreGoodsRes = await this.model('or_shop_goods').db(model.db()).updateMany(decreGoods);
            }

            if (decreGoodsLog.length) {
              addDecreGoodsLog = await this.model('or_shop_goodslog').db(model.db()).addMany(decreGoodsLog);
            }
          }

          if (!addGuestCardSubject && !addTempReserve && !updateDecreGoodsRes && !addDecreGoodsLog) {
            await model.rollback();
            return this.fail('处理赠送品项失败');
          }
        }

        // 如果有现金收益则增加收款帐号并记录收款金额
        if (data.alist.length) {
          let upAcco = [], adAccoLogs = [];
          for (var i = data.alist.length - 1; i >= 0; i--) {
            const aco = await this.model('or_shop_account').db(model.db()).where({id: data.alist[i].id}).find();

            upAcco.push({
              id: data.alist[i].id,
              balance: aco.balance + data.alist[i].money * 1
            });

            adAccoLogs.push({
              departmentid: shopid,
              type: 1,
              accountid: data.alist[i].id,
              ordertype: 'CZD',
              orderid: data.oid,
              money: data.alist[i].money,
              addtime: oinfo.addtime
            });
          }

          const upAcoRes = await this.model('or_shop_account').db(model.db()).updateMany(upAcco);

          const adAcoRes = await this.model('or_shop_accountlog').db(model.db()).addMany(adAccoLogs);

          if (!upAcoRes && !adAcoRes) {
            await model.rollback();
            return this.fail('收款失败');
          }
        }

        // 如果有业绩分配人员，则记录
        if (data.ulist.length) {
          let adxjLogs = [], adtcLogs = [];
          data.ulist.forEach((v) => {
            adxjLogs.push({
              orderid: data.oid,
              feattype: 'CZD',
              shopid: shopid,
              feat: v.money,
              bumenid: v.bumenid,
              xiaozuid: v.xiaozuid,
              userid: v.id,
              addtime: oinfo.addtime
            });

            adtcLogs.push({
              shopid: shopid,
              orderid: data.oid,
              ordertype: 'CZD',
              xianjinyeji: v.money,
              userid: v.id,
              bumenid: v.bumenid,
              xiaozuid: v.xiaozuid,
              addtime: oinfo.addtime,
              guestid: oinfo.guestid
            });
          });

          const adxjLogRes = await this.model('or_shop_yejixianjin').db(model.db()).addMany(adxjLogs);

          const adtcLogRes = await this.model('or_shop_yejiticheng').db(model.db()).addMany(adtcLogs);

          if (!adxjLogRes && !adtcLogRes) {
            await model.rollback();
            return this.fail('分配业绩失败');
          }
        }

        const res = await model.where({id: data.oid}).update({
          status: 1,
          auditorid: aid,
          gendanid: data.gdid * 1
        });

        if (!res) {
          await model.rollback();
          return this.fail('结账失败');
        }

        await model.commit();
        return this.success({code: 200, info: '结账成功', status: 1});
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('结账失败');
      }
    });
  }

  // 重新分配充值现金业绩
  async resetfenpeiAction() {
    const data = JSON.parse(this.post('data'));

    const oinfo = await this.model('or_shop_order').where({id: data.oid}).find();

    const isCanEditOrder = await this.isCanEditOrder(data.oid, 'CZD');
    if (!isCanEditOrder) {
      return this.fail('暂不允许操作其他店单据！');
    }

    if (oinfo.status > 1) {
      return this.fail('当前订单已经分配业绩提成');
    }

    if (!data.ulist.length) {
      return this.fail('分配业绩人员为空');
    }

    const shopid = this.shop_userinfo.departmentid;

    const model = this.model('or_shop_yejiticheng');

    await model.transaction(async() => {
      try {
        const yejiLogs = await model.where({shopid: shopid, orderid: data.oid, ordertype: 'CZD'}).select();

        if (yejiLogs.length) {
          const clearTcLogs = await model.where({shopid: shopid, orderid: data.oid, ordertype: 'CZD'}).delete();
          const clearYjLogs = await this.model('or_shop_yejixianjin').db(model.db()).where({orderid: data.oid, feattype: 'CZD', shopid: shopid}).delete();

          if (!clearTcLogs && !clearYjLogs) {
            await model.rollback();
            return this.fail('清除之前业绩失败');
          }
        }

        if (data.ulist.length) {
          let adYjLogs = [], adTcLogs = [];
          data.ulist.forEach((v) => {
            adYjLogs.push({
              orderid: data.oid,
              feattype: 'CZD',
              shopid: shopid,
              feat: v.money * 1,
              bumenid: v.bumenid,
              xiaozuid: v.xiaozuid,
              userid: v.id,
              addtime: oinfo.addtime
            });
            adTcLogs.push({
              shopid: shopid,
              orderid: data.oid,
              ordertype: 'CZD',
              xianjinyeji: v.money * 1,
              userid: v.id,
              bumenid: v.bumenid,
              xiaozuid: v.xiaozuid,
              addtime: oinfo.addtime,
              guestid: oinfo.guestid
            });
          });

          const adYjLogsRes = await this.model('or_shop_yejixianjin').db(model.db()).addMany(adYjLogs);

          const adTcLogsRes = await model.addMany(adTcLogs);

          if (!adYjLogsRes && !adTcLogsRes) {
            await model.rollback();
            return this.fail('重新分配失败');
          }
        }

        await model.commit();
        return this.success({code: 200, info: '分配成功'});
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('重新分配业绩失败');
      }
    });
  }

  // 完成充值流程
  async rechargeFinishAction() {
    const data = JSON.parse(this.post('retData'));

    const oinfo = await this.model('or_shop_order').where({id: data.oid}).find();

    const isCanEditOrder = await this.isCanEditOrder(data.oid, 'CZD');
    if (!isCanEditOrder) {
      return this.fail('暂不允许操作其他店单据！');
    }

    if (oinfo.status > 1) {
      return this.fail('当前订单已经分配业绩提成');
    }

    const shopid = this.shop_userinfo.departmentid;

    const aid = this.shop_userinfo.id;

    const time = Math.round(Date.now() / 1000);

    const model = this.model('or_shop_order');

    await model.transaction(async() => {
      try {
        /*
        * 1、先判断yejiticheng表是否有数据，如果有就先删除
        * 2、然后在重新添加新的提成信息，把业绩和提成都加入
        */

        const tcList = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: data.oid, ordertype: 'CZD'}).select();

        if (!think.isEmpty(tcList)) {
          const delTcListRes = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: data.oid, ordertype: 'CZD'}).delete();
          if (!delTcListRes) {
            await model.rollback();
            return this.fail('删除缓存数据失败');
          }
        }

        if (data.tclist.length) {
          let geng = [], addFenPei = [], addTiCheng = [], addPay = [];
          data.tclist.forEach((v) => {
            addTiCheng.push({
              shopid: shopid,
              orderid: data.oid,
              ordertype: 'CZD',
              addtype: v.addtype,
              xianjinyeji: v.money * 1,
              xianjinticheng: v.addtype == 0 ? v.ticheng * 1 : 0,
              qitaticheng: v.addtype == 1 ? v.ticheng * 1 : 0,
              xianjinjieti: v.xianjinjieti * 1,
              userid: v.id,
              bumenid: v.bumenid,
              xiaozuid: v.xiaozuid,
              addtime: oinfo.addtime,
              guestid: oinfo.guestid
            });

            if (!v.addtype) {
              addFenPei.push({
                orderid: data.oid,
                ordertype: 3,
                userid: v.id,
                type: 1,
                yeji: v.money * 1,
                tichengbi: Number(v.ticheng / v.money).toFixed(2),
                money: v.ticheng,
                addtime: oinfo.addtime
              });

              if (v.xianjinjieti > 0) {
                addFenPei.push({
                  orderid: data.oid,
                  ordertype: 3,
                  userid: v.id,
                  type: 5,
                  yeji: v.money * 1,
                  tichengbi: 0,
                  money: v.xianjinjieti * 1,
                  addtime: oinfo.addtime
                });
              }
            }

            if (v.addtype) {
              addPay.push({
                userid: v.id,
                category: 2,
                type: 4,
                money: v.ticheng,
                orderid: data.oid,
                ordertype: 3,
                time: oinfo.addtime,
                addtime: time
              });
            } else {
              addPay.push({
                userid: v.id,
                category: 2,
                type: 1,
                money: v.ticheng,
                orderid: data.oid,
                ordertype: 3,
                time: oinfo.addtime,
                addtime: time
              });
              if (v.xianjinjieti > 0) {
                addPay.push({
                  userid: v.id,
                  category: 2,
                  type: 5,
                  money: v.xianjinjieti,
                  orderid: data.oid,
                  ordertype: 3,
                  time: oinfo.addtime,
                  addtime: time
                });
              }
            }
          });

          if (geng.length) {
            const upTcRes = await this.model('or_shop_yejiticheng').db(model.db()).updateMany(geng);
            if (!upTcRes) {
              await model.rollback();
              return this.fail('更新业绩提成失败');
            }
          }
          if (addFenPei.length) {
            const adFpRes = await this.model('or_shop_fenpeiticheng').db(model.db()).addMany(addFenPei);
            if (!adFpRes) {
              await model.rollback();
              return this.fail('添加分配提成失败');
            }
          }
          if (addTiCheng.length) {
            const adTcRes = await this.model('or_shop_yejiticheng').db(model.db()).addMany(addTiCheng);
            if (!adTcRes) {
              await model.rollback();
              return this.fail('添加业绩提成失败');
            }
          }
          if (addPay.length) {
            const adPyRes = await this.model('or_shop_userbasepay').db(model.db()).addMany(addPay);
            if (!adPyRes) {
              await model.rollback();
              return this.fail('添加员工工资提成失败');
            }
          }
        }

        const fin = await model.where({id: data.oid}).update({status: 2, auditorid: aid});

        if (!fin) {
          await model.rollback();
          return this.fail('更改订单状态失败');
        }
        await model.commit();
        return this.success('充值完成');
      } catch (e) {
        // console.log(e);
        await model.rollback();
        return this.fail('提成分配失败');
      }
    });
  }

  // 已分配提成重新分配（反分配）
  async fanfenpeiAction() {
    const id = this.post('id');

    /// /////////////////////////////////////////////////////////////////////
    // 1、只删除分配的提成                                                //
    // 2、先删除or_shop_fenpeiticheng 和 or_shop_userbasepay里分配的提成  //
    // 3、先更新or_shop_yejiticheng表，把里面addtype为0的行现金提成变为0  //
    // 然后再把addtype为1的行删除                                      //
    // 4、最后把订单的已分配提成状态改为已结账                            //
    /// /////////////////////////////////////////////////////////////////////

    const oinfo = await this.model('or_shop_order').where({id: id}).find();

    const isCanEditOrder = await this.isCanEditOrder(id, 'CZD');
    if (!isCanEditOrder) {
      return this.fail('暂不允许操作其他店单据！');
    }
    if (oinfo.status < 2) {
      return this.fail('当前订单未分配提成');
    }

    const shopid = this.shop_userinfo.departmentid;

    const model = this.model('or_shop_order');

    await model.transaction(async() => {
      try {
        const tcOne = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: id, ordertype: 'CZD', addtype: 0}).select();

        const tcTwo = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: id, ordertype: 'CZD', addtype: 1}).select();

        let delTcRes = 1;
        let upOneRes = 1;
        let delPayRes = 1;
        let delFpRes = 1;

        if (tcTwo.length) {
          delTcRes = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: id, ordertype: 'CZD', addtype: 1}).delete();
        }

        if (tcOne.length) {
          const upOne = [];
          tcOne.forEach((v) => {
            upOne.push({
              id: v.id,
              xianjinticheng: 0,
              xianjinjieti: 0
            });
          });
          upOneRes = await this.model('or_shop_yejiticheng').db(model.db()).updateMany(upOne);

          delPayRes = await this.model('or_shop_userbasepay').db(model.db()).where({category: 2, orderid: id, ordertype: 3}).delete();

          delFpRes = await this.model('or_shop_fenpeiticheng').db(model.db()).where({orderid: id, ordertype: 3, type: 1}).delete();
        }

        if (!delTcRes && !upOneRes && !delPayRes && !delFpRes) {
          await model.rollback();
          return this.fail('反提成分配失败');
        }

        const zt = await model.where({id: id}).update({status: 1});

        if (!zt) {
          await model.rollback();
          return this.fail('更改订单状态失败');
        }
        await model.commit();
        return this.success({code: 200, info: '反分配提成成功', status: 1});
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('反分配失败');
      }
    });
  }
}
